package Part6_对象流;

import org.junit.Test;
import java.io.*;

/**
 * ClassName: ObjectStreamTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.22 22:55
 */
public class ObjectStreamTest {

    /**
     * 序列化过程
     */
    @Test
    public void test1() throws IOException {
        File file = new File("object.txt");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));

        oos.writeUTF("黄河之水天上来");
        oos.writeObject("啦啦啦啦啦");

        oos.flush();
        oos.close();
    }

    /**
     * 反序列化过程
     */
    @Test
    public void test2() throws IOException, ClassNotFoundException {
        File file = new File("object.txt");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

        String str = ois.readUTF();//对应writeUTF()
        System.out.println(str);

        Object o = ois.readObject();//对应writeObject()
        System.out.println(o);

        ois.close();
    }

    /**
     * 自定义类的序列化和反序列化
     * 1、序列化：
     */
    @Test
    public void test3() throws IOException{
        File file = new File("object.txt");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));

        //序列化过程
        Person person1 = new Person("Tom",12);
        //如果自定义类没有Serializable接口：NotSerializableException（不能序列化的异常）
        oos.writeObject(person1);
        oos.flush();

        //Account如果实现序列化接口：NotSerializableException
        Person person2 = new Person("Jerry",20,new Account(2000));
        oos.writeObject(person2);
        oos.flush();

        oos.close();
    }

    /**
     * 自定义类的序列化和反序列化
     * 2、反序列化：
     */
    @Test
    public void test4() throws IOException, ClassNotFoundException {
        File file = new File("object.txt");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

        //反序列化
        //自定义类没有标识的serialVersionUID且类有变化的情况下：InvalidClassException（无效类的异常）
        //有UID唯一标识、类有改变的情况下，不会出异常
        Person person1 = (Person) ois.readObject();
        System.out.println(person1);

        Person person2 = (Person) ois.readObject();
        System.out.println(person2);

        ois.close();
    }
}
